﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using Prism.Commands;
using Prism.Mvvm;
using ZhaoxiLearningWpf.Common;
using ZhaoxiLearningWpf.DataAccess;
using ZhaoxiLearningWpf.DataAccess.DataEntity;
using ZhaoxiLearningWpf.Model;

namespace ZhaoxiLearningWpf.ViewModel
{
    public class LoginViewModel : BindableBase
    {
        public LoginModel loginModel { get; set; } = new LoginModel();

        public CommandBase CloseCmd { get; set; }

        public CommandBase LoginCmd { get; set; }

        private bool isEnabled=true;

        public bool IsEnabled {
            get { return isEnabled; }
            set { isEnabled = value;
                LoginCmd.RasieCanExecuteChanged();
            }
        }


        public LoginViewModel()
        {

            CloseCmd = new CommandBase();
            CloseCmd.DoExecute = o => {
                ( o as Window )?.Close();
            };
            CloseCmd.DoCanExecute = o => true;

            LoginCmd = new CommandBase();
            LoginCmd.DoExecute = Login;
            LoginCmd.DoCanExecute = o => IsEnabled;
        }

        void Login(object o)
        {
            loginModel.ErrorMsg = "";

            if (string.IsNullOrEmpty(loginModel.UserName)) {
                loginModel.ErrorMsg = "请输入用户名！";
                return;
            }
            if (string.IsNullOrEmpty(loginModel.Password)) {
                loginModel.ErrorMsg = "请输入密码！";
                return;
            }
            if (string.IsNullOrEmpty(loginModel.Validation)) {
                loginModel.ErrorMsg = "请输入验证码！";
                return;
            }
            if( loginModel.Validation.ToUpper() != "QNMX") {
                loginModel.ErrorMsg = "验证码错误！";
                return;
            }

            Task.Run(() => {
                try {
                    Application.Current.Dispatcher.Invoke(()=> IsEnabled = false);

                    UserEntity uesr = SQLAceess.GetSQLInstance().GetUserInfo(loginModel.UserName, loginModel.Password);
                    if (uesr == null)
                        throw new Exception("用户名密码错误！");

                    GlobalValues.UserInfo = uesr;

                    this.loginModel.ErrorMsg = "登录成功";

                    Application.Current.Dispatcher.Invoke(() => (o as Window).DialogResult = false);
                }
                catch (Exception ex) {
                    this.loginModel.ErrorMsg = ex.Message;
                }
                finally {
                    Application.Current.Dispatcher.Invoke(() => IsEnabled = true);
                }

            });
        }

    }
}
